#include "notification_manager.h"

#include <QApplication>
#include <QDebug>
#include <QEasingCurve>
#include <QGraphicsDropShadowEffect>
#include <QPropertyAnimation>
#include <QRect>
#include <QScreen>
#include <QSizePolicy>

// NotificationWidget 实现
NotificationWidget::NotificationWidget(const NotificationData& data, QWidget* parent)
    : QFrame(parent),
      m_data(data),
      m_iconLabel(nullptr),
      m_titleLabel(nullptr),
      m_messageLabel(nullptr),
      m_closeButton(nullptr),
      m_mainLayout(nullptr),
      m_headerLayout(nullptr),
      m_contentLayout(nullptr),
      m_progressBar(nullptr),
      m_positionAnimation(nullptr),
      m_progressAnimation(nullptr),
      m_autoHideTimer(nullptr)
{
    setupUI();
    setupAnimations();
    applyStyle();  // 在动画设置之后调用，确保进度条已创建

    // 设置自动隐藏定时器
    if (m_data.duration > 0) {
        m_autoHideTimer = new QTimer(this);
        m_autoHideTimer->setSingleShot(true);
        m_autoHideTimer->setInterval(m_data.duration);
        connect(m_autoHideTimer, &QTimer::timeout, this, &NotificationWidget::onAutoHideTimeout);
    }
}

NotificationWidget::~NotificationWidget() {}

void NotificationWidget::setupUI()
{
    setFixedWidth(380);     // 固定宽度，高度自适应
    setMinimumHeight(80);   // 最小高度
    setMaximumHeight(200);  // 最大高度
    setFrameStyle(QFrame::NoFrame);

    // 创建主布局
    m_mainLayout = new QVBoxLayout(this);
    m_mainLayout->setContentsMargins(0, 0, 0, 0);
    m_mainLayout->setSpacing(0);

    // 创建内容框架
    QFrame* contentFrame = new QFrame(this);
    contentFrame->setObjectName("contentFrame");

    QVBoxLayout* contentMainLayout = new QVBoxLayout(contentFrame);
    contentMainLayout->setContentsMargins(20, 15, 20, 15);
    contentMainLayout->setSpacing(8);

    // 创建标题行布局
    m_headerLayout = new QHBoxLayout();
    m_headerLayout->setContentsMargins(0, 0, 0, 0);
    m_headerLayout->setSpacing(12);

    // 图标标签
    m_iconLabel = new QLabel(this);
    m_iconLabel->setFixedSize(30, 30);
    m_iconLabel->setAlignment(Qt::AlignCenter);
    m_iconLabel->setText(getIconText(m_data.type));
    // 样式在applyStyle()中统一设置
    m_headerLayout->addWidget(m_iconLabel);

    // 标题标签
    if (!m_data.title.isEmpty()) {
        m_titleLabel = new QLabel(m_data.title, this);
        // 样式在applyStyle()中统一设置
        m_headerLayout->addWidget(m_titleLabel);
    }

    m_headerLayout->addStretch();

    // 关闭按钮
    m_closeButton = new QPushButton("✕", this);
    m_closeButton->setFixedSize(22, 22);
    // 样式在applyStyle()中统一设置
    connect(m_closeButton, &QPushButton::clicked, this, &NotificationWidget::onCloseButtonClicked);
    m_headerLayout->addWidget(m_closeButton);

    contentMainLayout->addLayout(m_headerLayout);

    // 消息标签
    m_messageLabel = new QLabel(m_data.message, this);
    m_messageLabel->setWordWrap(true);
    // 样式在applyStyle()中统一设置
    contentMainLayout->addWidget(m_messageLabel);

    // 进度条（如果有持续时间）
    if (m_data.duration > 0) {
        // 创建进度条容器
        QFrame* progressContainer = new QFrame(this);
        progressContainer->setFixedHeight(3);
        progressContainer->setStyleSheet(
            "QFrame {"
            "    background-color: rgba(0, 0, 0, 0.1);"
            "    border-radius: 1px;"
            "}");

        // 创建进度条填充
        m_progressBar = new QFrame(progressContainer);
        m_progressBar->setFixedHeight(3);
        m_progressBar->move(0, 0);

        contentMainLayout->addWidget(progressContainer);
    }

    m_mainLayout->addWidget(contentFrame);

    // 确保布局自动调整大小
    setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Minimum);
}

QString NotificationWidget::getIconText(NotificationType type)
{
    switch (type) {
        case NotificationType::Info:
            return "ℹ️";  // 或者试试: "🔵" "📘" "ℹ️" "💬"
        case NotificationType::Warning:
            return "⚠️";  // 或者试试: "🟡" "📳" "⚡" "🔔"
        case NotificationType::Error:
            return "❌";  // 或者试试: "🔴" "⛔" "🚫" "💥"
        case NotificationType::Success:
            return "✅";  // 或者试试: "🟢" "🎉" "👍" "💚"
        default:
            return "💡";
    }
}

QString NotificationWidget::getTypeColors(NotificationType type, QString& borderColor,
                                          QString& backgroundColor, QString& iconColor)
{
    switch (type) {
        case NotificationType::Info:
            borderColor = "#3498db";
            backgroundColor =
                "qlineargradient(x1:0, y1:0, x2:0, y2:1, "
                "stop:0 rgba(235, 243, 253, 0.95), "
                "stop:1 rgba(214, 233, 251, 0.95))";
            iconColor = "#2980b9";
            break;
        case NotificationType::Warning:
            borderColor = "#f39c12";
            backgroundColor =
                "qlineargradient(x1:0, y1:0, x2:0, y2:1, "
                "stop:0 rgba(254, 249, 231, 0.95), "
                "stop:1 rgba(252, 243, 207, 0.95))";
            iconColor = "#e67e22";
            break;
        case NotificationType::Error:
            borderColor = "#e74c3c";
            backgroundColor =
                "qlineargradient(x1:0, y1:0, x2:0, y2:1, "
                "stop:0 rgba(253, 237, 236, 0.95), "
                "stop:1 rgba(250, 219, 216, 0.95))";
            iconColor = "#c0392b";
            break;
        case NotificationType::Success:
            borderColor = "#27ae60";
            backgroundColor =
                "qlineargradient(x1:0, y1:0, x2:0, y2:1, "
                "stop:0 rgba(234, 250, 241, 0.95), "
                "stop:1 rgba(213, 244, 230, 0.95))";
            iconColor = "#229954";
            break;
    }
    return "";
}

void NotificationWidget::applyStyle()
{
    QString borderColor, backgroundColor, iconColor;
    getTypeColors(m_data.type, borderColor, backgroundColor, iconColor);

    // 主框架样式 - 只给主框架设置边框
    QString mainStyle = QString(
                            "QFrame {"
                            "    border: 1px solid rgba(0, 0, 0, 0.1);"
                            "    border-left: 4px solid %1;"  // 左侧彩色条作为类型指示
                            "    border-radius: 8px;"
                            "    background: %2;"
                            "}"
                            "QFrame#contentFrame {"
                            "    border: none;"             // 内容框架不需要边框
                            "    background: transparent;"  // 透明背景
                            "}")
                            .arg(borderColor, backgroundColor);

    setStyleSheet(mainStyle);

    // 设置图标颜色和样式
    if (m_iconLabel) {
        m_iconLabel->setStyleSheet(
            "QLabel {"
            "    font-size: 16px;"
            "    font-weight: bold;"
            "    border: none;"  // 移除图标边框
            "    background-color: transparent;"
            "}");
    }

    // 设置标题样式
    if (m_titleLabel) {
        m_titleLabel->setStyleSheet(
            "QLabel {"
            "    font-weight: bold;"
            "    font-size: 15px;"
            "    color: #2c3e50;"
            "    border: none;"
            "    background: transparent;"
            "    padding: 0px;"
            "}");
    }

    // 设置消息样式
    if (m_messageLabel) {
        m_messageLabel->setStyleSheet(
            "QLabel {"
            "    font-size: 13px;"
            "    color: #34495e;"
            "    line-height: 1.4;"
            "    border: none;"
            "    background: transparent;"
            "    padding: 0px;"
            "    margin-left: 36px;"
            "}");
    }

    // 设置关闭按钮样式
    if (m_closeButton) {
        m_closeButton->setStyleSheet(
            "QPushButton {"
            "    min-width: 30px;"
            "    min-height: 30px;"
            "    max-width: 30px;"
            "    max-height: 30px;"
            "    border: none;"
            "    background: rgba(0, 0, 0, 0.05);"
            "    font-size: 11px;"
            "    font-weight: bold;"
            "    color: #999;"
            "    border-radius: 15px;"
            "}"
            "QPushButton:hover {"
            "    background: rgba(0, 0, 0, 0.15);"
            "    color: #666;"
            "}"
            "QPushButton:pressed {"
            "    background: rgba(0, 0, 0, 0.25);"
            "    color: #333;"
            "}");
    }

    // 设置进度条颜色
    if (m_progressBar) {
        m_progressBar->setStyleSheet(QString("QFrame {"
                                             "    background-color: %1;"
                                             "    border-radius: 1px;"
                                             "}")
                                         .arg(borderColor));
    }

    // 添加更柔和的阴影效果
    QGraphicsDropShadowEffect* shadowEffect = new QGraphicsDropShadowEffect(this);
    shadowEffect->setBlurRadius(15);
    shadowEffect->setColor(QColor(0, 0, 0, 40));  // 更透明的阴影
    shadowEffect->setOffset(0, 2);
    setGraphicsEffect(shadowEffect);
}

void NotificationWidget::setupAnimations()
{
    // 位置动画
    m_positionAnimation = new QPropertyAnimation(this, "pos", this);
    m_positionAnimation->setDuration(400);
    m_positionAnimation->setEasingCurve(QEasingCurve::OutBack);

    // 进度条动画
    if (m_data.duration > 0 && m_progressBar) {
        m_progressAnimation = new QPropertyAnimation(m_progressBar, "geometry", this);
        m_progressAnimation->setDuration(m_data.duration);
        m_progressAnimation->setEasingCurve(QEasingCurve::Linear);
    }
}

void NotificationWidget::showNotification()
{
    if (!parent()) return;

    QWidget* parentWidget = qobject_cast<QWidget*>(parent());
    if (!parentWidget) return;

    // 获取当前Y位置（已由NotificationManager设置）
    int currentY = y();

    // 设置初始位置（在屏幕右侧外面）
    QPoint startPos(parentWidget->width() + 50, currentY);  // 稍微向外一点，确保完全隐藏
    QPoint endPos(parentWidget->width() - width() - 20, currentY);

    setVisible(true);
    move(startPos);

    // 配置显示动画 - 只使用位置动画
    m_positionAnimation->setStartValue(startPos);
    m_positionAnimation->setEndValue(endPos);
    m_positionAnimation->start();

    // 开始进度条动画
    if (m_progressAnimation) {
        int progressWidth = 340;  // 固定宽度380减去左右边距40

        // 设置初始状态：填满进度条
        QRect startRect(0, 0, progressWidth, 3);
        QRect endRect(0, 0, 0, 3);  // 最终宽度为0

        m_progressBar->setGeometry(startRect);

        m_progressAnimation->setStartValue(startRect);
        m_progressAnimation->setEndValue(endRect);
        m_progressAnimation->start();
    }

    // 开始自动隐藏定时器
    if (m_autoHideTimer) {
        m_autoHideTimer->start();
    }
}

void NotificationWidget::hideNotification()
{
    // 防止重复调用
    if (property("hiding").toBool()) {
        return;
    }
    setProperty("hiding", true);

    if (m_autoHideTimer) {
        m_autoHideTimer->stop();
    }

    if (m_progressAnimation && m_progressAnimation->state() == QAbstractAnimation::Running) {
        m_progressAnimation->stop();
    }

    if (!parent()) {
        emit notificationClosed();
        return;
    }

    QWidget* parentWidget = qobject_cast<QWidget*>(parent());
    if (!parentWidget) {
        emit notificationClosed();
        return;
    }

    // 使用简单的位置动画
    QPropertyAnimation* hideAnimation = new QPropertyAnimation(this, "pos", this);
    hideAnimation->setDuration(300);
    hideAnimation->setEasingCurve(QEasingCurve::InBack);

    QPoint startPos = pos();
    QPoint endPos(parentWidget->width() + 50, y());

    hideAnimation->setStartValue(startPos);
    hideAnimation->setEndValue(endPos);

    connect(hideAnimation, &QPropertyAnimation::finished, this,
            [this]() { emit notificationClosed(); });

    connect(hideAnimation, &QPropertyAnimation::finished, hideAnimation,
            &QPropertyAnimation::deleteLater);

    hideAnimation->start();

    // 安全机制：如果动画在500ms内没有完成，强制发送关闭信号
    QTimer::singleShot(500, this, [this]() {
        if (this && property("hiding").toBool()) {
            emit notificationClosed();
        }
    });
}

void NotificationWidget::onCloseButtonClicked() { hideNotification(); }

void NotificationWidget::onAutoHideTimeout() { hideNotification(); }

// NotificationManager 实现
NotificationManager* NotificationManager::m_instance = nullptr;

NotificationManager* NotificationManager::instance()
{
    if (!m_instance) {
        m_instance = new NotificationManager();
    }
    return m_instance;
}

NotificationManager::NotificationManager(QObject* parent) : QObject(parent), m_parentWidget(nullptr)
{
}

NotificationManager::~NotificationManager() { clearAll(); }

void NotificationManager::showNotification(const QString& title, const QString& message,
                                           NotificationType type, int duration)
{
    if (m_notificationQueue.size() >= MAX_QUEUE_SIZE) {
        m_notificationQueue.dequeue();
        qWarning() << "通知队列已满，移除最旧的通知";
    }
    NotificationData data(title, message, type, duration);
    m_notificationQueue.enqueue(data);

    QTimer::singleShot(0, this, &NotificationManager::processNotificationQueue);
}

void NotificationManager::showInfo(const QString& message, int duration)
{
    showNotification("信息", message, NotificationType::Info, duration);
}

void NotificationManager::showWarning(const QString& message, int duration)
{
    showNotification("警告", message, NotificationType::Warning, duration);
}

void NotificationManager::showError(const QString& message, int duration)
{
    showNotification("错误", message, NotificationType::Error, duration);
}

void NotificationManager::showSuccess(const QString& message, int duration)
{
    showNotification("成功", message, NotificationType::Success, duration);
}

void NotificationManager::setParentWidget(QWidget* parent) { m_parentWidget = parent; }

void NotificationManager::clearAll()
{
    m_notificationQueue.clear();

    for (NotificationWidget* notification : m_activeNotifications) {
        notification->hideNotification();
    }
}

void NotificationManager::onNotificationClosed()
{
    NotificationWidget* notification = qobject_cast<NotificationWidget*>(sender());
    if (!notification) return;

    m_activeNotifications.removeOne(notification);
    notification->deleteLater();

    repositionNotifications();

    // 处理队列中的下一个通知
    QTimer::singleShot(100, this, &NotificationManager::processNotificationQueue);
}

void NotificationManager::processNotificationQueue()
{
    if (m_notificationQueue.isEmpty() || !m_parentWidget) {
        return;
    }

    if (m_activeNotifications.size() >= MAX_NOTIFICATIONS) {
        return;  // 达到最大显示数量，等待有通知关闭
    }

    showNextNotification();
}

void NotificationManager::showNextNotification()
{
    if (m_notificationQueue.isEmpty() || !m_parentWidget) {
        return;
    }

    NotificationData data = m_notificationQueue.dequeue();

    NotificationWidget* notification = new NotificationWidget(data, m_parentWidget);
    connect(notification, &NotificationWidget::notificationClosed, this,
            &NotificationManager::onNotificationClosed);

    // 先添加到列表中，然后计算位置
    m_activeNotifications.append(notification);

    // 让控件自动调整大小
    notification->adjustSize();

    // 计算Y位置 - 根据前面通知的实际高度累加
    int yPos = MARGIN_TOP;
    for (int i = 0; i < m_activeNotifications.size() - 1; ++i) {
        yPos += m_activeNotifications[i]->height() + NOTIFICATION_SPACING;
    }

    notification->move(m_parentWidget->width(), yPos);
    notification->showNotification();
}

void NotificationManager::repositionNotifications()
{
    int currentY = MARGIN_TOP;

    for (int i = 0; i < m_activeNotifications.size(); ++i) {
        NotificationWidget* notification = m_activeNotifications[i];
        int targetX = m_parentWidget->width() - notification->width() - MARGIN_RIGHT;

        QPropertyAnimation* repositionAnim = new QPropertyAnimation(notification, "pos", this);
        repositionAnim->setDuration(200);
        repositionAnim->setEasingCurve(QEasingCurve::OutCubic);
        repositionAnim->setStartValue(notification->pos());
        repositionAnim->setEndValue(QPoint(targetX, currentY));

        connect(repositionAnim, &QPropertyAnimation::finished, repositionAnim,
                &QPropertyAnimation::deleteLater);
        repositionAnim->start();

        // 累加当前通知的高度，为下一个通知计算位置
        currentY += notification->height() + NOTIFICATION_SPACING;
    }
}